<template>
  <div class="reward-punishments-container">
    <div class="header">
      <h2>奖惩管理</h2>
      <div class="header-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          <span>新增</span>
        </el-button>
        <el-button type="success" @click="handleExportExcel" style="margin-left: 10px;">
          <el-icon><Download /></el-icon>
          <span>导出Excel</span>
        </el-button>
      </div>
    </div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
        v-model="searchForm.employee_name"
        placeholder="搜索员工姓名"
        style="width: 200px; margin-right: 10px;"
        clearable
        @clear="handleSearch"
        @input="handleSearch"
        @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-select
        v-model="searchForm.types"
        multiple
        placeholder="选择奖惩类型"
        style="width: 200px"
        @change="handleSearch"
      >
        <el-option label="奖励" value="奖励"></el-option>
        <el-option label="惩罚" value="惩罚"></el-option>
        <el-option label="警告" value="警告"></el-option>
        <el-option label="通报表扬" value="通报表扬"></el-option>
      </el-select>
    </div>
    <div class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        :fit="true"
        size="small"
        header-cell-class-name="table-header"
        row-class-name="table-row"
      >
        <el-table-column prop="employee_name" label="员工姓名" min-width="120" show-overflow-tooltip />
        <el-table-column prop="type" label="奖惩类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === '奖励' ? 'success' : scope.row.type === '惩罚' ? 'danger' : scope.row.type === '警告' ? 'warning' : 'info'">
              {{ scope.row.type }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="date" label="奖惩时间" width="120" />
        <el-table-column prop="reason" label="奖惩原因" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="warning" @click="handleView(scope.row)">
              <el-icon><View /></el-icon>
              <span>查看</span>
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)" style="margin-left: 8px;">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)" style="margin-left: 8px;">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!-- 新增/编辑/查看奖惩记录对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加奖惩记录' : dialogType === 'edit' ? '编辑奖惩记录' : '查看奖惩记录'"
      width="80%"
      style="max-width: 1200px"
      :destroy-on-close="true"
      class="reward-dialog adaptive-dialog"
      top="5vh"
    >
      <div class="dialog-content adaptive-dialog-content">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          :disabled="dialogType === 'view'"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="员工姓名" prop="employee_id">
                <el-select
                  v-model="form.employee_id"
                  placeholder="请选择员工"
                  style="width: 100%"
                  :disabled="dialogType === 'view'"
                >
                  <el-option
                    v-for="emp in employees"
                    :key="emp.id"
                    :label="emp.name"
                    :value="emp.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="奖惩类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择类型" style="width: 100%" :disabled="dialogType === 'view'">
                  <el-option label="奖励" value="奖励" />
                  <el-option label="惩罚" value="惩罚" />
                  <el-option label="警告" value="警告" />
                  <el-option label="通报表扬" value="通报表扬" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="奖惩时间" prop="date">
                <el-date-picker v-model="form.date" type="date" value-format="YYYY-MM-DD" style="width: 100%" :disabled="dialogType === 'view'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label=" " prop="placeholder" label-width="0">
                <span></span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="奖惩原因" prop="reason">
                <el-input v-model="form.reason" type="textarea" :rows="3" :disabled="dialogType === 'view'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            v-if="dialogType !== 'view'"
            type="primary"
            @click="submitForm"
            :loading="submitting"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Download, View, Edit, Delete } from '@element-plus/icons-vue'
import { employeeAPI } from '../api/index'
import api from '../api/index'
import { rewardPunishmentAPI } from '../api'

const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchForm = ref({ employee_name: '', types: ['惩罚'] })
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({ id: null, employee_id: '', type: '', reason: '', date: '' })
const rules = {
  employee_id: [ { required: true, message: '请选择员工', trigger: 'change' } ],
  type: [ { required: true, message: '请选择奖惩类型', trigger: 'change' } ],
  reason: [ { required: true, message: '请输入奖惩原因', trigger: 'blur' } ],
  date: [ { required: true, message: '请选择奖惩时间', trigger: 'change' } ]
}
const employees = ref([])
const submitting = ref(false)

// 处理导出Excel
const handleExportExcel = async () => {
  try {
    const res = await rewardPunishmentAPI.exportExcel()
    const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = '奖惩列表.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(url)
    ElMessage.success('导出成功')
  } catch (e) {
    ElMessage.error('导出失败，请稍后重试')
    console.error('导出奖惩列表失败:', e)
  }
}

// 获取员工列表
const loadEmployees = async () => {
  const res = await employeeAPI.getAll(1, 1000)
  employees.value = res.data.data || []
}

// 获取奖惩记录列表（分页+搜索）
const getRewardList = async () => {
  loading.value = true
  try {
    // 先查所有员工
    const empRes = await employeeAPI.getAll(1, 1000)
    const allEmps = empRes.data.data || []
    // 过滤员工
    let filteredEmps = allEmps
    if (searchForm.value.employee_name) {
      filteredEmps = allEmps.filter(emp => emp.name.includes(searchForm.value.employee_name))
    }
    // 拉取奖惩
    const reqs = filteredEmps.map(emp =>
      api.get(`/api/employees/${emp.id}/reward_punishments`).then(rpRes =>
        (rpRes.data || []).map(rp => ({ ...rp, employee_name: emp.name, employee_id: emp.id }))
      )
    )
    let allRewards = (await Promise.all(reqs)).flat()

    // 在分页和类型过滤前，按日期倒序排序所有奖惩记录
    allRewards.sort((a, b) => new Date(b.date) - new Date(a.date));

    // 根据奖惩类型过滤
    if (searchForm.value.types && searchForm.value.types.length > 0) {
      allRewards = allRewards.filter(rp => searchForm.value.types.includes(rp.type))
    }

    // 应用分页
    total.value = allRewards.length
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = allRewards.slice(start, end)

  } catch (e) {
    ElMessage.error('加载奖惩记录失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  getRewardList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  getRewardList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  getRewardList()
}

const handleAdd = () => {
  dialogType.value = 'add'
  form.value = { id: null, employee_id: '', type: '', reason: '', date: '' }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogType.value = 'view'
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除此奖惩记录吗？', '警告', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await api.delete(`/api/employees/${row.employee_id}/reward_punishments/${row.id}`)
      ElMessage.success('删除成功')
      getRewardList()
    } catch (e) {
      ElMessage.error('删除失败')
    }
  })
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      if (dialogType.value === 'add') {
        await api.post(`/api/employees/${form.value.employee_id}/reward_punishments`, form.value)
        ElMessage.success('添加成功')
      } else if (dialogType.value === 'edit') {
        await api.put(`/api/employees/${form.value.employee_id}/reward_punishments/${form.value.id}`, form.value)
        ElMessage.success('修改成功')
      }
      dialogVisible.value = false
      getRewardList()
    } catch (e) {
      ElMessage.error('操作失败')
    } finally {
      submitting.value = false
    }
  })
}

onMounted(() => {
  loadEmployees()
  getRewardList()
})

watch(() => searchForm.value.employee_name, () => {
  handleSearch()
})

watch(() => searchForm.value.types, () => {
  handleSearch()
})
</script>

<style scoped>
.reward-punishments-container {
  padding: 20px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}
.header-buttons {
  display: flex;
  align-items: center;
}
.search-bar {
  margin-bottom: 20px;
  width: 100%;
  display: flex;
  align-items: center;
}
.table-header {
  font-weight: bold;
  background: #fafbfc;
}
.table-row:hover {
  background: #f5f7fa !important;
}
.table-container {
  width: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.03);
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
}
.pagination-container {
  margin-top: 0px;
  display: flex;
  justify-content: flex-end;
}
.dialog-footer {
  text-align: right;
}

/* Apply styles from Certificates.vue for better consistency */
:deep(.el-table) {
  margin-bottom: 20px;
  border: none;
}

:deep(.el-table__header) {
  background-color: #F5F7FA;
}

:deep(.el-table th) {
  background-color: #F5F7FA !important;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table td) {
  padding: 8px 0;
}

:deep(.el-table .el-table__fixed-right) {
  background-color: #fff;
}

:deep(.el-table .el-table__fixed-right th) {
  background-color: #F5F7FA !important;
}

:deep(.el-table .el-table__fixed-right td) {
  background-color: #fff;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
  padding-bottom: 0;
}

:deep(.el-dialog__footer) {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  background-color: #f9f9f9;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
  border-radius: 4px;
  /* margin-left: 8px;  already added inline */
}

.adaptive-dialog .el-dialog {
  margin: 0 auto;
  top: 5vh !important;
  transform: none !important;
}

.header-buttons .el-button span {
  margin-left: 4px;
}
</style> 